package com.ruoyi.web.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.Api;
import com.ruoyi.system.service.IApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * Api接口管理Controller
 *
 * @author ruoyi
 * @date 2022-05-19
 */
@RestController
@RequestMapping("/system/api")
public class ApiController extends BaseController
{
    @Autowired
    private IApiService apiService;

    @Autowired
    private TokenService tokenService;
    /**
     * 查询Api接口管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:api:list')")
    @GetMapping("/list")
    public TableDataInfo list(Api api)
    {
        startPage();
        List<Api> list = apiService.selectApiList(api);
        return getDataTable(list);
    }

    /**
     * 导出Api接口管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:api:export')")
    @Log(title = "Api接口管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Api api)
    {
        List<Api> list = apiService.selectApiList(api);
        ExcelUtil<Api> util = new ExcelUtil<Api>(Api.class);
        return util.exportExcel(list, "api");
    }

    /**
     * 获取Api接口管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:api:query')")
    @GetMapping(value = "/{apiId}")
    public AjaxResult getInfo(@PathVariable("apiId") String apiId)
    {
        return AjaxResult.success(apiService.selectApiById(apiId));
    }

    /**
     * 新增Api接口管理
     */
    @PreAuthorize("@ss.hasPermi('system:api:add')")
    @Log(title = "Api接口管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Api api)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        apiService.insertApi(api);
        api.setCreateBy(String.valueOf(loginUser.getUser().getUserId()));
        api.setApiId(IdUtils.simpleUUID());
        api.setCreateTime(new Date());
        if (api.getRequestParams().equals("")){
            api.setRequestParams("{}");
        }
        if (api.getReturnExample().equals("")){
            api.setReturnExample("{}");
        }
        String requestParams = beautifulJson(api.getRequestParams());
        String returnExample = beautifulJson(api.getReturnExample());
        api.setRequestParams(requestParams);
        api.setReturnExample(returnExample);
//        apiService.insertApi(api)
        return toAjax(apiService.insertApi(api));
    }

    /**
     * 修改Api接口管理
     */
    @PreAuthorize("@ss.hasPermi('system:api:edit')")
    @Log(title = "Api接口管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Api api)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        api.setUpdateBy(String.valueOf(loginUser.getUser().getUserId()));
        String requestParams = beautifulJson(api.getRequestParams());
        String requestBody = beautifulJson(api.getRequestBody());
        String returnExample = beautifulJson(api.getReturnExample());
        api.setRequestParams(requestParams);
        api.setRequestBody(requestBody);
        api.setReturnExample(returnExample);
        api.setUpdateTime(new Date());
        return toAjax(apiService.updateApi(api));
    }

    /**
     * 删除Api接口管理
     */
    @PreAuthorize("@ss.hasPermi('system:api:remove')")
    @Log(title = "Api接口管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{apiIds}")
    public AjaxResult remove(@PathVariable String[] apiIds)
    {
        return toAjax(apiService.deleteApiByIds(apiIds));
    }

    public String beautifulJson(String s){
        JSONObject object = JSONObject.parseObject(s);
        String pretty = JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
        return pretty;
    }
}